package com.power.config;

import cn.hutool.core.util.ObjectUtil;
import com.power.contant.AuthConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * feign拦截器
 * 作用 : 处理服务之间调用没有Token的亲情况
 */

@Component
public class FeignInterceptor implements RequestInterceptor { // 对每一次的请求


    @Override
    public void apply(RequestTemplate requestTemplate) {

        //处理服务之间调用没有token的情况
        //获取上一次请求的请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        if (ObjectUtil.isNotNull(request)) {
            String authorizationValue = request.getHeader(AuthConstants.AUTHORIZATION);
            if (StringUtils.hasText(authorizationValue)) {
                //获取Token
                String token = authorizationValue.replaceFirst(AuthConstants.BEARER, "");
                //判断Token是否有值
                if (StringUtils.hasText(token)) {
                    //将上一个请求头中Token放到下一个请求头中
                    requestTemplate.header(AuthConstants.AUTHORIZATION, AuthConstants.BEARER + token);
                    return;
                }

            }
        }

        //处理请求不是来自于自己项目前端的 没有token的情况
        requestTemplate.header(AuthConstants.AUTHORIZATION, AuthConstants.BEARER + "08d6374e-290a-46a6-9fc0-954b3fa51d04");

    }
}
